package fourfaith.com.ff_sl21_app.fragment;

import android.content.Context;
import android.graphics.Point;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.content.ContextCompat;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.BounceInterpolator;
import android.view.animation.Interpolator;
import android.view.animation.LinearInterpolator;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amap.api.maps.AMap;
import com.amap.api.maps.CameraUpdateFactory;
import com.amap.api.maps.Projection;
import com.amap.api.maps.SupportMapFragment;
import com.amap.api.maps.TextureMapView;
import com.amap.api.maps.UiSettings;
import com.amap.api.maps.model.BitmapDescriptorFactory;
import com.amap.api.maps.model.LatLng;
import com.amap.api.maps.model.LatLngBounds;
import com.amap.api.maps.model.Marker;
import com.amap.api.maps.model.MarkerOptions;
import com.amap.api.maps.model.animation.Animation;
import com.amap.api.maps.model.animation.ScaleAnimation;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;

import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import fourfaith.com.ff_sl21_app.DeviceActivity;
import fourfaith.com.ff_sl21_app.R;
import fourfaith.com.ff_sl21_app.utils.Constants;
import fourfaith.com.ff_sl21_app.utils.JsonRequest;
import fourfaith.com.ff_sl21_app.utils.RequestQueueSingleton;
import fourfaith.com.ff_sl21_app.utils.ResponseResult;


public class DeviceMapFragment extends SupportMapFragment {

    private Context context;
    private LinearLayout mapParam,rootLinear,emptyValue,loadValue;
    private TextureMapView mapView;
    private AMap aMap;
    private View mapLayout;
    public List<Map<String, Object>> dataList = new ArrayList<>();
    private OnFragmentInteractionListener mListener;
    private DecimalFormat df = new DecimalFormat("#.###");

    private Marker lastMark = null;
    //缓存stcd对应marker
    private Map<String, Marker> stcdMarker = new HashMap<>();

    //地图坐标点弹出层
    private TextView siteName, siteCode;


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        context = getActivity();
        mapLayout = inflater.inflate(R.layout.fragment_device_map, container, false);
        mapView = (TextureMapView) mapLayout.findViewById(R.id.mapView);
        mapView.onCreate(savedInstanceState);
        if (aMap == null) {
            aMap = mapView.getMap();
            UiSettings mUiSettings = aMap.getUiSettings();
            //禁止旋转
            mUiSettings.setRotateGesturesEnabled(false);
            //禁止缩放按钮
            mUiSettings.setZoomControlsEnabled(false);

        }

        mapParam = (LinearLayout) mapLayout.findViewById(R.id.mapParam);
        rootLinear = (LinearLayout) mapLayout.findViewById(R.id.rootLinear);
        emptyValue = (LinearLayout) mapLayout.findViewById(R.id.emptyValue);
        loadValue = (LinearLayout) mapLayout.findViewById(R.id.loadValue);

        siteName = (TextView) mapLayout.findViewById(R.id.siteName);
        siteCode = (TextView) mapLayout.findViewById(R.id.siteCode);

        aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
            @Override
            public void onMapLoaded() {
                DeviceActivity.mapIsLoaded = true;
            }
        });

        aMap.setOnMarkerClickListener(new AMap.OnMarkerClickListener() {

            @Override
            public boolean onMarkerClick(Marker marker) {
                if (aMap != null) {
                    jumpAndShowInfo(marker.getTitle());
                }

                return true;
            }

        });

        return mapLayout;
    }

    /**
     * 在地图上添加marker
     */
    public void addMarkersToMap() {

        lastMark = null;
        aMap.clear();
        stcdMarker.clear();
        dataList = DeviceActivity.dataList;
        Marker _tmpMarker = null;
        if (dataList != null && dataList.size() > 0) {
            LatLngBounds.Builder builder = new LatLngBounds.Builder();

            for (int i = 0; i < dataList.size(); i++) {

                Map<String, Object> map = dataList.get(i);

                if (map.get("deviceLgtd") != null && map.get("deviceLttd") != null) {

                    MarkerOptions option = new MarkerOptions();

                    double lat = new BigDecimal(map.get("deviceLttd").toString()).doubleValue();
                    double lng = new BigDecimal(map.get("deviceLgtd").toString()).doubleValue();

                    option.position(new LatLng(lat, lng));

                    Integer iconId = getIconIdBySttp(map.get("deviceSttp").toString());
                    option.icon(BitmapDescriptorFactory.fromResource(iconId));
//                    option.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE));

                    option.title(map.get("deviceCode").toString());
                    option.snippet(map.get("deviceName").toString());
                    _tmpMarker = aMap.addMarker(option);
                    startGrowAnimation(_tmpMarker);
                    builder.include(new LatLng(lat, lng));
                    stcdMarker.put(map.get("deviceCode").toString(), _tmpMarker);
                }

            }

            final LatLngBounds bounds = builder.build();

            if (!DeviceActivity.mapIsLoaded) {
                final Marker final_tmpMarker = _tmpMarker;
                aMap.setOnMapLoadedListener(new AMap.OnMapLoadedListener() {
                    @Override
                    public void onMapLoaded() {
                        DeviceActivity.mapIsLoaded = true;
                        mapAniCamera(bounds, final_tmpMarker);
                    }
                });
            } else {
                mapAniCamera(bounds, _tmpMarker);
            }

        }

    }

    private int getIconIdBySttp(String sttp) {
        int result = R.mipmap.sttp_0;

        switch (sttp) {
            case "1":
                result = R.mipmap.sttp_1;
                break;
            case "2":
                result = R.mipmap.sttp_2;
                break;
            case "3":
                result = R.mipmap.sttp_3;
                break;
            case "4":
                result = R.mipmap.sttp_4;
                break;
        }

        return result;
    }

    /**
     * 移动地图
     *
     * @param bounds
     * @param marker
     */
    private void mapAniCamera(LatLngBounds bounds, Marker marker) {
        if (bounds != null && !bounds.southwest.equals(bounds.northeast))
            // 移动地图，所有marker自适应显示。LatLngBounds与地图边缘10像素的填充区域
            aMap.animateCamera(CameraUpdateFactory.newLatLngBounds(bounds, 10));
        else if (marker != null)
            aMap.animateCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
    }

    /**
     * 坐标点生成动画
     */
    private void startGrowAnimation(Marker marker) {
        Animation animation = new ScaleAnimation(0, 1, 0, 1);
        animation.setInterpolator(new LinearInterpolator());
        //整个移动所需要的时间
        animation.setDuration(1000);
        //设置动画
        marker.setAnimation(animation);
        //开始动画
        marker.startAnimation();
    }

    private String getAddress(String address) {
        StringBuilder sb = new StringBuilder();
        String tmp = address;
        while (tmp.length() > 14) {
            sb.append(tmp.substring(0, 14));
            sb.append("\n");
            tmp = tmp.substring(14, tmp.length());
        }
        sb.append(tmp);
        return sb.toString();
    }

    /**
     * 详情层隐藏
     */
    public void hideDetail() {
        mapParam.setVisibility(View.GONE);
        if (lastMark != null)
            lastMark.setIcon(BitmapDescriptorFactory.fromResource(R.mipmap.video));
    }

    public interface OnFragmentInteractionListener {
        void onFragmentInteraction(Uri uri);
    }

    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        mapView.onSaveInstanceState(outState);
    }

    @Override
    public void onResume() {
        super.onResume();
        mapView.onResume();
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }

    public void jumpAndShowInfo(String stcd) {

        Marker marker = stcdMarker.get(stcd);
        siteName.setText(marker.getSnippet());
        siteCode.setText("("+stcd+")");
        mapParam.setVisibility(View.VISIBLE);
        loadValue.setVisibility(View.VISIBLE);
        emptyValue.setVisibility(View.GONE);
        rootLinear.setVisibility(View.GONE);
        if (marker != null) {

            lastMark = marker;

            jumpPoint(marker);
            aMap.animateCamera(CameraUpdateFactory.changeLatLng(marker.getPosition()));
            mapParam.setVisibility(View.VISIBLE);

            //请求最新要素信息
            final String url = Constants.readtimeDataByStcd + "?stcd=" + stcd + "&userId=" + Constants.getUserId();

            RequestQueue mQueue = RequestQueueSingleton.getInstance(getActivity()).getRequestQueue();
            JsonRequest<ResponseResult> jsonRequest = new JsonRequest<>(Request.Method.GET, url, ResponseResult.class,
                    new Response.Listener<ResponseResult>() {

                        @Override
                        public void onResponse(ResponseResult responseResult) {
                            if (responseResult.getCode().equals("200")) {

                                rootLinear.removeAllViews();

                                JSONObject dataObj = (JSONObject) responseResult.getData();

                                JSONArray viewHead = dataObj.getJSONArray("viewHead");
                                JSONArray sysUserFactorList = dataObj.getJSONArray("sysUserFactorList");

                                LinearLayout playout = new LinearLayout(context);
                                if(!dataObj.get("model").equals("")){
                                    JSONObject model = dataObj.getJSONObject("model");
                                    loadValue.setVisibility(View.GONE);
                                    emptyValue.setVisibility(View.GONE);
                                    rootLinear.setVisibility(View.VISIBLE);
                                    for (int i=0; i<viewHead.size();i++){

                                        JSONObject jObj = sysUserFactorList.getJSONObject(i);
                                        String factor = jObj.getString("factor");
                                        BigDecimal v = model.getBigDecimal(factor);

                                        LinearLayout layout = new LinearLayout(context);
                                        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                                        layoutParams.height=Constants.dip2px(context,30);
                                        layout.setLayoutParams(layoutParams);
                                        TextView fname = new TextView(context);
                                        TextView fvalue = new TextView(context);

                                        fname.setLayoutParams(layoutParams);
                                        fname.setTextColor(ContextCompat.getColorStateList(context, R.color.itemLeftColor));
                                        fname.setTextSize(12);
                                        fname.setText(viewHead.get(i)+"：");
                                        fname.setGravity(Gravity.CENTER|Gravity.END);

                                        layout.addView(fname);

                                        fvalue.setLayoutParams(layoutParams);
                                        fvalue.setTextColor(ContextCompat.getColorStateList(context, R.color.itemRightColor));
                                        fvalue.setTextSize(12);
                                        fvalue.setText(v==null?"":df.format(v.doubleValue()));
                                        fvalue.setGravity(Gravity.CENTER|Gravity.START);
                                        layout.addView(fvalue);

                                        playout.addView(layout);
                                        if(i%2==1 || i==viewHead.size()-1){

                                            if(i%2==0 && i==viewHead.size()-1){
                                                //插入空布局
                                                LinearLayout layout2 = new LinearLayout(context);
                                                layout2.setLayoutParams(layoutParams);
                                                playout.addView(layout2);
                                            }

                                            rootLinear.addView(playout);

                                            playout = new LinearLayout(context);

                                            LinearLayout.LayoutParams playoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
                                            playoutParams.height=Constants.dip2px(context,30);
                                            playout.setLayoutParams(playoutParams);
                                            playout.setOrientation(LinearLayout.HORIZONTAL);

                                        }


                                    }

                                    //添加采集时间
                                    LinearLayout layout = new LinearLayout(context);
                                    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 3);
                                    layoutParams.height=Constants.dip2px(context,30);
                                    layout.setLayoutParams(layoutParams);
                                    TextView fname = new TextView(context);
                                    TextView fvalue = new TextView(context);

                                    fname.setLayoutParams(layoutParams);
                                    fname.setTextColor(ContextCompat.getColorStateList(context, R.color.itemLeftColor));
                                    fname.setTextSize(12);
                                    fname.setText("采集时间：");
                                    fname.setGravity(Gravity.CENTER|Gravity.END);

                                    layout.addView(fname);

                                    LinearLayout.LayoutParams layoutParams2 = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1);
                                    layoutParams2.height=Constants.dip2px(context,30);
                                    fvalue.setLayoutParams(layoutParams2);
                                    fvalue.setTextColor(ContextCompat.getColorStateList(context, R.color.itemRightColor));
                                    fvalue.setTextSize(12);
                                    fvalue.setText(model.get("tm").toString());
                                    fvalue.setGravity(Gravity.CENTER|Gravity.START);
                                    layout.addView(fvalue);

                                    playout.addView(layout);
                                    rootLinear.addView(playout);
                                }else{
                                    emptyValue.setVisibility(View.VISIBLE);
                                    rootLinear.setVisibility(View.GONE);
                                    loadValue.setVisibility(View.GONE);
                                }

                            } else {
                                Toast.makeText(getActivity(), responseResult.getMsg(), Toast.LENGTH_SHORT).show();
                            }


                        }

                    }, new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    emptyValue.setVisibility(View.VISIBLE);
                    rootLinear.setVisibility(View.GONE);
                    loadValue.setVisibility(View.GONE);
                    if (error.networkResponse == null) {
                        Toast.makeText(getActivity(), "连接超时，请求不到网络数据", Toast.LENGTH_SHORT).show();
                    } else {
                        if (error.getMessage() == null) {
                            Toast.makeText(getActivity(), "接口服务器异常", Toast.LENGTH_SHORT).show();
                        } else {
                            Toast.makeText(getActivity(), error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }
                }

            });
            mQueue.add(jsonRequest);
        }
    }

    /**
     * marker点击时跳动一下
     */
    public void jumpPoint(final Marker marker) {
        final Handler handler = new Handler();
        final long start = SystemClock.uptimeMillis();
        Projection proj = aMap.getProjection();
        final LatLng markerLatlng = marker.getPosition();
        Point markerPoint = proj.toScreenLocation(markerLatlng);
        markerPoint.offset(0, -100);
        final LatLng startLatLng = proj.fromScreenLocation(markerPoint);
        final long duration = 1500;

        final Interpolator interpolator = new BounceInterpolator();
        handler.post(new Runnable() {
            @Override
            public void run() {
                long elapsed = SystemClock.uptimeMillis() - start;
                float t = interpolator.getInterpolation((float) elapsed / duration);
                double lng = t * markerLatlng.longitude + (1 - t) * startLatLng.longitude;
                double lat = t * markerLatlng.latitude + (1 - t) * startLatLng.latitude;
                marker.setPosition(new LatLng(lat, lng));
                if (t < 1.0) {
                    handler.postDelayed(this, 16);
                }
            }
        });
    }
}
